package com.sangmo.fts.user.service;

import com.sangmo.boot.framework.common.session.UserSession;
import com.sangmo.boot.framework.data.filter.NativeQueryBuilder;
import com.sangmo.boot.framework.data.filter.PageResult;
import com.sangmo.boot.framework.data.filter.PageSearch;
import com.sangmo.boot.framework.plugin.dataview.crud.service.DelegateViewService;
import com.sangmo.boot.framework.plugin.dataview.crud.service.ViewService;
import com.sangmo.boot.framework.plugin.dataview.spi.jpa.NativeQueryBuilderFactory;
import com.sangmo.fts.basic.model.Notice;
import com.sangmo.fts.clazz.model.Clazz;
import com.sangmo.fts.clazz.service.ClazzEntityService;
import com.sangmo.fts.clazz.service.ClazzService;
import com.sangmo.fts.user.model.User;
import com.sangmo.fts.user.service.UserEntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserService extends DelegateViewService<User> {

    @Autowired
    private UserEntityService userEntityService;

    @Autowired
    private ClazzService clazzService;

    @Override
    protected ViewService<User> getEntityService() {
        return userEntityService;
    }

    public PageResult<User> clazzMemberSearch(PageSearch ps) {
        Long currentUserId = (Long) UserSession.getUserInterface().getId();
        Clazz clazz = clazzService.findByStudentId(currentUserId);
        NativeQueryBuilder builder = NativeQueryBuilderFactory.create()
                .selectForm("SELECT a.* FROM user a ")
                .where(" EXISTS(select uc.user_id from user_clazz uc where clazz_id = :clazzId and uc.user_id = a.id) AND a.ex_role_id = '4' ")
                .where(ps)
                .putVariable("clazzId", clazz.getId())
                .transform(User.class);
        return builder.buildPage();
    }
}
